package com.softstao.guoyu.ui.activity.shop;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.softstao.guoyu.R;
import com.softstao.guoyu.base.BaseActivity;
import com.softstao.guoyu.global.GsonManager;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.model.me.Address;
import com.softstao.guoyu.model.me.AddressList;
import com.softstao.guoyu.model.shop.CartGoods;
import com.softstao.guoyu.model.shop.OrderCondition;
import com.softstao.guoyu.model.shop.OrderId;
import com.softstao.guoyu.model.shop.OrderProductInfo;
import com.softstao.guoyu.mvp.interactor.me.AddressInteractor;
import com.softstao.guoyu.mvp.interactor.shop.GoodsInteractor;
import com.softstao.guoyu.mvp.presenter.me.AddressPresenter;
import com.softstao.guoyu.mvp.presenter.shop.GoodsPresenter;
import com.softstao.guoyu.mvp.viewer.me.AddressListViewer;
import com.softstao.guoyu.mvp.viewer.shop.AddOrderViewer;
import com.softstao.guoyu.ui.activity.me.AddAddressActivity;
import com.softstao.guoyu.ui.activity.me.AddressListActivity;
import com.softstao.guoyu.ui.activity.sale.ToAgentOrderListActivity;
import com.softstao.guoyu.ui.baseAdapter.RecycleViewBaseAdapter;
import com.softstao.guoyu.ui.baseAdapter.RecycleViewHolder;
import com.softstao.guoyu.widget.HintDialog;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.widget.FullyLinearLayoutManager;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by vaikus on 2017/6/9.
 */

public class OrderConfirmActivity extends BaseActivity implements AddressListViewer, AddOrderViewer {

    @AIPresenter(presenter = AddressPresenter.class, interactor = AddressInteractor.class)
    AddressPresenter addressPresenter;
    @AIPresenter(presenter = GoodsPresenter.class, interactor = GoodsInteractor.class)
    GoodsPresenter presenter;

    @BindView(R.id.total_price)
    TextView totalPrice;
    @BindView(R.id.add_address)
    TextView addAddress;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.mobile)
    TextView mobile;
    @BindView(R.id.address)
    TextView addressView;
    @BindView(R.id.address_detail)
    RelativeLayout addressDetail;
    @BindView(R.id.list_view)
    RecyclerView listView;
//    @BindView(R.id.memo)
//    EditText memo;
    @BindView(R.id.loading)
    RelativeLayout loading;
    @BindView(R.id.submit_btn)
    TextView submitBtn;
    private List<Address> addressLists = new ArrayList<>();
    private List<CartGoods> goodsList = new ArrayList<>();
    private List<OrderProductInfo> orderProductInfos = new ArrayList<>();
    private RecycleViewBaseAdapter<CartGoods> adapter;
    private OrderCondition condition = new OrderCondition();
    private final int ADD_ADDRESS = 1;
    private final int CHOOSE_ADDRESS = 2;
    private Address address;
    private int allPrice = 0;
    private List<CartGoods> checkedGoods = new ArrayList<>();

    @Override
    public int _ContentView() {
        return R.layout.activity_order_confirm;
    }

    @Override
    public void initView() {
        initTitle("确认下单");
        goodsList = (List<CartGoods>) getIntent().getSerializableExtra("goods");

        adapter = new RecycleViewBaseAdapter<CartGoods>(goodsList, R.layout.layout_order_confirm_item) {
            @Override
            public void convert(RecycleViewHolder holder, CartGoods goods) {
                RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                holder.itemView.setLayoutParams(layoutParams);
                if (goods.getImg() != null && !goods.getImg().equals("")) {
                    Glide.with(context).load(goods.getImg()).into((ImageView) holder.getView(R.id.img));
                } else {
                    ((ImageView) holder.getView(R.id.img)).setImageResource(R.mipmap.default_im);
                }
                holder.setText(R.id.name, goods.getName())
                        .setText(R.id.price, getResources().getString(R.string.rmb) + LZUtils.priceFormat(goods.getPrice()))
                        .setText(R.id.num, "x" + goods.getNum())
                        .setText(R.id.total_price, getResources().getString(R.string.rmb) + LZUtils.priceFormat(goods.getSubtotal()));
            }
        };
        listView.setAdapter(adapter);
        listView.setLayoutManager(new FullyLinearLayoutManager(this));
        adapter.notifyDataSetChanged();

        for (int i = 0; i < goodsList.size(); i++) {
            allPrice += goodsList.get(i).getSubtotal();

            OrderProductInfo orderProductInfo = new OrderProductInfo();
            orderProductInfo.setProductId(goodsList.get(i).getProductId());
            orderProductInfo.setCount(goodsList.get(i).getNum());
            orderProductInfos.add(orderProductInfo);
        }
        totalPrice.setText(Html.fromHtml("合计：<font color='#fb4a9b'>" + getResources().getString(R.string.rmb) + LZUtils.priceFormat(allPrice) + "</font>"));

        addressPresenter = new AddressPresenter();
        addressPresenter.setInteractor(new AddressInteractor());
        addressPresenter.setViewer(this);
        getAddress();
    }

    @OnClick({R.id.submit_btn, R.id.add_address, R.id.address_detail})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.submit_btn:
                submitBtn.setEnabled(false);
                addOrder();
                break;
            case R.id.add_address:
                Intent addIntent = new Intent(getContext(), AddAddressActivity.class);
                addIntent.putExtra("cart", true);
                addIntent.putExtra("flag", 1);
                startActivityForResult(addIntent, ADD_ADDRESS);
                break;
            case R.id.address_detail:
                Intent detailIntent = new Intent(getContext(), AddressListActivity.class);
                detailIntent.putExtra("cart", true);
                startActivityForResult(detailIntent, CHOOSE_ADDRESS);
                break;
        }
    }

    private void setAddress(Address address) {
        name.setText("接收人：" + address.getName());
        mobile.setText(address.getMobile());
        addressView.setText("收货地址：" + address.getProvinceName() + address.getCityName() +
                address.getAreaName() + address.getAddress());
        condition.setAddressId(address.getAddressId());
    }

    @Override
    public void getAddress() {
        addressPresenter.getAddress(SharePreferenceManager.getInstance().getAgentId());
    }

    @Override
    public void changeDefault() {

    }

    @Override
    public void deleteAddress() {

    }

    @Override
    public void getList(AddressList addressList) {
        if (addressList != null) {
            if (addressList.getAddressList() != null && addressList.getAddressList().size() != 0) {
                addAddress.setVisibility(View.GONE);
                addressDetail.setVisibility(View.VISIBLE);
                addressLists.clear();
                addressLists.addAll(addressList.getAddressList());
                for (int i = 0; i < addressLists.size(); i++) {
                    if (addressLists.get(i).isDefaultX() == true) {
                        setAddress(addressLists.get(i));
                    }
                }
            } else {
                addAddress.setVisibility(View.VISIBLE);
                addressDetail.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void changeResult(AddressList addressList) {

    }

    @Override
    public void deleteResult(Object result) {

    }

    @Override
    public void addOrder() {
        loading.setVisibility(View.VISIBLE);
        condition.setAgentId(SharePreferenceManager.getInstance().getAgentId());
//        condition.setRemark(memo.getText().toString());
        condition.setOrderProductInfo(GsonManager.getInstance().getGson().toJson(orderProductInfos));
        presenter.addOrder(condition);
    }

    @Override
    public void addResult(OrderId orderId) {
        loading.setVisibility(View.GONE);
        showSuccess();
    }

    private void showSuccess() {
        HintDialog dialog = new HintDialog(context, R.style.MyDialog);
        dialog.getWindow().setLayout(getScreenWidth() - LZUtils.dipToPix(context, 55) * 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setIcon(R.mipmap.hint_icon_success);
        dialog.setTitle("订单提交");
        dialog.setContentVisible();
        dialog.setContent("订单已成功提交，\n请关注订单状态的改变！");
        dialog.setConfirm("查看订单");
        dialog.getConfirm().setOnClickListener(v -> {
            dialog.dismiss();
            startActivity(new Intent(context, ToAgentOrderListActivity.class).putExtra("orderState", ""));
            finish();
        });
        dialog.getCancelIc().setOnClickListener(v -> {
            dialog.dismiss();
            startActivity(new Intent(context, ToAgentOrderListActivity.class).putExtra("orderState", ""));
            finish();
        });
        dialog.show();
    }

    @Override
    protected void error(String msg) {
        super.error(msg);
        loading.setVisibility(View.GONE);
        submitBtn.setEnabled(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CHOOSE_ADDRESS:
                    address = (Address) data.getSerializableExtra("address");
                    setAddress(address);
                    break;
                case ADD_ADDRESS:
                    address = (Address) data.getSerializableExtra("address");
                    addAddress.setVisibility(View.GONE);
                    addressDetail.setVisibility(View.VISIBLE);
                    setAddress(address);
                    break;
            }
        }
    }
}
